
package com.itheima.controller.backend.security;

import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class SpringSecurityUserService implements UserDetailsService {
    //查找服务，实现查询数据库
    @Autowired
    private UserService userService;

    //根据用户名查询数据库中用户信息
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user  = userService.LoadUserByname(username);
        List<GrantedAuthority> list = new ArrayList<>();
        // 从数据库中查询用户
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在！");
        }
        // 查询用户的角色
        HashSet<Role> roles = userService.loadRolesByUserId(user.getId());
        user.setRoles(roles);
        //获取Spring Security框架中返回授权user对象
        org.springframework.security.core.userdetails.User SecurityUser = new org.springframework.security.core.userdetails.User(username,user.getPassword(),list);
        return SecurityUser;
    }
}

